const { defineConfig } = require('@vue/cli-service')
const Mock = require('mockjs')
const bodyParser = require('body-parser')

const data = Mock.mock({
  'list|50': [
    {
      id: '@id',
      name: '@cname',
      'title|+1': 1,
      img: '@image(100x100, @color)',
      count: '@integer(1, 10)',
      check: false,
    },
  ],
})

const userList = [
  {
    id: 1,
    username: 'admin',
    password: '123',
  },
  {
    id: 2,
    username: 'devin',
    password: '123',
  },
]

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    setupMiddlewares(middles, { app }) {
      app.use(bodyParser.json())
      // 测试接口
      app.get('/api/get-test', (req, res) => {
        res.send({
          data: data.list,
        })
      })
      // 登陆接口
      app.post('/api/login', (req, res) => {
        const { username, password } = req.body

        const flag = userList.some(
          (user) => user.username === username && user.password === password
        )
        if (flag) {
          res.send({
            code: 0,
            msg: 'success',
            data: {
              token: `${username}_${Date.now()}`,
            },
          })
        } else {
          res.send({
            code: -1,
            msg: '登陆失败，请重试',
          })
        }
      })

      // 分页接口
      // 测试接口
      app.get('/api/list', (req, res) => {
        const { page = 1, size = 10 } = req.query
        res.send({
          code: 0,
          msg: 'success',
          data: {
            total: data.list.length,
            list: data.list.slice((page - 1) * size, page * size),
          },
        })
      })

      return middles
    },
  },
})
